<?php

//include_once './system/core/chat/define.php';

class post
{
    static function login()
    {
        $conn = $GLOBALS['conn'];
        $username = isset($_POST['username']) ? $_POST['username'] : "";
        $password = hash("sha256", isset($_POST['password']) ? $_POST['password'] : "");
        $sql = "SELECT * FROM user";
        $result = mysqli_query($conn, $sql);
        if (!$result) {
            die("database-error");
        }
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            if ($row['username'] == $username || $row['email'] == $username) {
                if ($row['password'] == $password) {
                    if ($row['is_ban'] == "yes") {
                        $ban_reason = $row['ban_reason'];
                        die(USER_IS_BAN . $ban_reason);
                    } else {
                        cookie::set("isLogin", "yes")
                            ->set("username", $username)
                            ->set("nickname", $row['nickname'])
                            ->set("room_xcid", "chat")
                            ->set("password-part1", substr($password, 0, 20))
                            ->set("password-part2", substr($password, 20, 20))
                            ->set("password-part3", substr($password, 40, 20))
                            ->set("password-part4", substr($password, 60, 4))
                            ->set("isAdmin", $row['is_admin']);
                        die(LOGIN_SUCCESSFUL);
                    }
                } else {
                    die(PASSWORD_WRONG);
                }
            }
        }
        die(USER_NOT_EXIST);
    }

    static function register()
    {
        $username = $_POST['username'];
        $password = hash("sha256", $_POST['password']);
        $nickname = $_POST['nickname'];
        $email = $_POST['email'];
        $conn = $GLOBALS['conn'];
        $result = mysqli_query($conn, "select * from user");
        if (!$result) {
            die("database-error");
        }
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            if ($row['username'] == $username) {
                die("username-exist");
            }
            if ($row['email'] == $email) {
                die("email-exist");
            }
        }
        $x = dbTool::insert("user", ["username", "nickname","password","email","is_ban","ban_reason","is_admin"],[$username,$nickname,$password,$email,'','','']);
        if ($x['status']=="success"){
            die("register-successful");
        }else if ($x['status']=="fail"){
            die("database-error");
        }
//        $sql = "INSERT INTO user(username,nickname,password,email,is_ban,ban_reason,is_admin)VALUES('$username','$nickname','$password','$email','','','')";
//        $register_result = mysqli_query($conn, $sql);
//        if (!$register_result) {
//            die("database-error");
//        }
//        die("register-successful");
    }

    static function getCAPTCHA()
    {
        updateLoginStatus();
        try {
            $a = random_int(1111, 9999);
            $address = "";
            if (isset($_POST['address'])) {
                $address = $_POST['address'];
            } else {
                die("null-email");
            }
            $b = xc_mail($address, CAPTCHA_MAIL_TITLE,  CAPTCHA_MAIL_CONTENT_1 . "<b><strong><i>" . $a . "</i></strong></b>" . CAPTCHA_MAIL_CONTENT_2);
            switch ($b['status']) {
                case "successful":
                    die("successful&" . $a);
                case "fail":
                    die("fail&" . $b['reason']);
                case "send_wait":
                    $t = $b['wait_time'];
                    die("wait&" . $t);
            }
        } catch (Exception $e) {
            die($e->getMessage());
        }
    }

    static function getRoomInfo()
    {
        updateLoginStatus();
        $xcid = $_POST['xcid'];
        $conn = $GLOBALS['conn'];
        $userList = array();
        $resultUser = mysqli_query($conn, "SELECT * FROM user");
        if (!$resultUser) {
            die("database-error");
        }
        while ($row = mysqli_fetch_array($resultUser, MYSQLI_ASSOC)) {
            $userList[$row['username']] = $row['nickname'];
        }
        $result = mysqli_query($conn, "SELECT * FROM room_list");
        if (!$result) {
            die("database-error");
        }
        $data = array();
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            if ($row['xcid'] == $xcid) {
                $data['name'] = $row['name'];
                $data['description'] = $row['description'];
                $data['xcid'] = $row['xcid'];
                $data['creator'] = $row['creator'];
                $data['creator_name'] = isset($userList[$row['creator']]) ? $userList[$row['creator']] : $row['creator'];
                $data['create_time'] = $row['create_time'];
                $value = json_encode($data);
                echo $value;
                return $data;
            }
        }
    }

    static function getMessageList()
    {
        updateLoginStatus();
        $xcid = $_POST['xcid'];
        $conn = $GLOBALS['conn'];
        $userList = array();
        $resultUser = mysqli_query($conn, "SELECT * FROM user");
        if (!$resultUser) {
            die("database-error");
        }
        while ($row = mysqli_fetch_array($resultUser, MYSQLI_ASSOC)) {
            $userList[$row['username']] = $row['nickname'];
        }
//        die($xcid);
        $result = mysqli_query($conn, "SELECT * FROM $xcid");
        if (!$result) {
            die("database-error");
        }
        $result_data = array();
        $counter = 0;
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $temp = array();
            $temp['name'] = $userList[$row['user']];
            switch ($row['type']) {
                case "NORMAL_TEXT":
                    $temp['content'] = stringTool::decode($row['content'], XCGZS_SECRET, true);
                    break;
            }
            $temp['user'] = $row['user'];
            $temp['reply_user'] = $row['reply_user'];
            $temp['time'] = $row['time'];
//            if (in_array(cookie::get('username'),$row['dz_list']))
            $temp['dz_ed'] = in_array(stringTool::encode(cookie::get('username'), XCGZS_SECRET, true), json_decode($row['dz_list'], true));
            $temp['dz_counter'] = 0 + $row['dz_counter'];
            $temp['dz_list'] = $row['dz_list'];
            $temp['id'] = $row['xcid'];
            $temp['reply_id'] = $row['reply_id'];
            $temp['reply_name'] = $userList[$row['reply_user'] != "" ? $row['reply_user'] : "root"];
            $sql = "SELECT creator FROM room_list WHERE xcid='$xcid'";
            $room_creator_result = mysqli_query($conn, $sql);
            $room_creator = "";
            while ($room_creator_row = mysqli_fetch_array($room_creator_result, MYSQLI_ASSOC)) {
                $room_creator = $room_creator_row['creator'];
            }
            $temp['canEdit'] = $row['user'] == cookie::get('username') || cookie::get('isAdmin') == "yes" || cookie::get('username') == $room_creator;
            $result_data[$counter++] = json_encode($temp);
        }
        die(json_encode($result_data));
    }

    static function snt()
    {
        updateLoginStatus();
        $content = str_replace("<", "&lt;", str_replace(">", "&gt;", $_POST['content']));
        $content = stringTool::encode($content, XCGZS_SECRET, true);
        $replyXCID = isset($_POST['replyXCID']) ? $_POST['replyXCID'] : "root";
        $replyUser = isset($_POST['replyUser']) ? $_POST['replyUser'] : "root";
//        print_r($_POST['replyUser']);
//        die();
        $user = cookie::get('username');
        $conn = $GLOBALS['conn'];
        $room = getRoomXCID(true);
        $time = date("Y-m-d H:i");
        $xcid = "message-" . genXCID(true);
        $dz_list = json_encode(array());
        $sql = "INSERT INTO $room (`user`,`type`,`content`,`time`,`xcid`,`dz_list`,`dz_counter`,`reply_id`,`reply_user`) VALUES ('$user','NORMAL_TEXT','$content','$time','$xcid','$dz_list',0,'$replyXCID','$replyUser')";
        $result = mysqli_query($conn, $sql);
        if (!$result) {
//            die("database-error");
            die("数据库错误" . mysqli_error($conn));
        }
        die("send-successful");
    }

    static function dz()
    {
        $data = array();
        updateLoginStatus();
        $id = $_POST['id'];
        $conn = $GLOBALS['conn'];
        $room = getRoomXCID(true);
        $result = mysqli_query($conn, "SELECT * FROM $room");
        if (!$result) {
            die(DATABASE_ERROR);
        }
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            if ($row['xcid'] == $id) {
                $dz_list = json_decode($row['dz_list'], true);
                $dz_list_new = array();
                $dz_counter = $row['dz_counter'];
                if (in_array(stringTool::encode(cookie::get('username'), XCGZS_SECRET, true), $dz_list)) {
                    $dz_list_new = arrayTool::remove($dz_list, stringTool::encode(cookie::get('username'), XCGZS_SECRET, true));
                } else {
                    $dz_list_new = arrayTool::add($dz_list, stringTool::encode(cookie::get('username'), XCGZS_SECRET, true));
                }
                $dz_counter = count($dz_list_new);
                $dz_list_json = json_encode($dz_list_new);
                $sql_update = "UPDATE $room SET dz_list='$dz_list_json',dz_counter='$dz_counter' WHERE xcid='$id'";
                $result_update = mysqli_query($conn, $sql_update);
                if (!$result_update) {
                    $data['status'] = "database-error";
                    $data['reason'] = mysqli_error($conn);
                    die(json_encode($data));
                }
                $data['status'] = "successful";
                $data['data'] = $dz_counter;
                $data['dz_ed'] = in_array(stringTool::encode(cookie::get('username'), XCGZS_SECRET, true), $dz_list_new);
                die(json_encode($data));
            }
        }
        $data['status'] = "error";
        $data['reason'] = "MESSAGE_NOT_EXIST";
        die(json_encode($data));
    }

    static function del()
    {
        $id = $_POST['id'];
        $conn = $GLOBALS['conn'];
        $room = getRoomXCID(true);
        $result_get = mysqli_query($conn, "SELECT * FROM $room");
        if (!$result_get) {
            die("database-error");
        }
        while ($row = mysqli_fetch_array($result_get, MYSQLI_ASSOC)) {
            if ($row['xcid'] == $id) {
                $result = mysqli_query($conn, "DELETE FROM $room WHERE xcid='$id'");
                if (!$result) {
                    die("database-error");
                }
                $result_del = mysqli_query($conn, "DELETE FROM $room WHERE reply_id='$id'");
                if (!$result_del) {
                    die("database-error");
                }
                die("delete-successful");
            }
        }
        die("message-not-exist");
    }

    static function editMessage()
    {
        $data = array();
        $room = getRoomXCID(true);
        $id = $_POST['id'];
        $content = stringTool::encode($_POST['content'], XCGZS_SECRET, true);
        $conn = $GLOBALS['conn'];
        $sql = "UPDATE $room SET content='$content' WHERE xcid='$id'";
        $result = mysqli_query($conn, $sql);
        if (!$result) {
            $data['status'] = "database-error";
            $data['reason'] = mysqli_error($conn);
            die(json_encode($data));
        }
        $data['status'] = "successful";
        $data['xcid'] = $id;
        $data['content'] = stringTool::decode($content, XCGZS_SECRET, true);
        die(json_encode($data));
    }

    static function saveRoomName()
    {
        $id = $_POST['xcid'];
        $new_name = $_POST['new_name'];
        $conn = $GLOBALS['conn'];
        $data = array();
        $sql = "UPDATE room_list SET name='$new_name' WHERE xcid='$id'";
        $result = mysqli_query($conn, $sql);
        if (!$result) {
            $data['status'] = "database-error";
            $data['reason'] = mysqli_error($conn);
            die(json_encode($data));
        }
        $data['status'] = "successful";
        die(json_encode($data));
    }

    static function saveRoomDescription()
    {
        $id = $_POST['xcid'];
        $new_desc = $_POST['new_desc'];
        $conn = $GLOBALS['conn'];
        $data = array();
        $sql = "UPDATE room_list SET room_list.description='$new_desc' WHERE xcid='$id'";
        $result = mysqli_query($conn, $sql);
        if (!$result) {
            $data['status'] = "database-error";
            $data['reason'] = mysqli_error($conn);
            die(json_encode($data));
        }
        $data['status'] = "successful";
        die(json_encode($data));
    }
}